package cn.otrue.patienthealthmanager.utils;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import cn.otrue.patienthealthmanager.http.HttpCons;

public class SendImageToRefund {
	private String newName = "image.jpg";
	private String uploadFile;
	private String actionUrl = HttpCons.SAVEURL;
	public static int WIN = 15;
	private Context context;
	private Handler handler;

	public SendImageToRefund(String uploadfile, Context context,Handler handler) {
		this.uploadFile = uploadfile;
		this.context = context;
		this.handler = handler;
	}
/**
 * 开启线程，开始上传商品图片
 * @describe 上传商品图片到服务器
 * @author BGX
 * @time 2015-4-26
 */
	public void startThread(){
		try {
			ThreadManager.execute(new Runnable() {
				@Override
				public void run() {
					uploadFile();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 从文件上传图片到服务器
	 * 
	 * @describe 在线程中调用该方法，本类中有全局的路径变量是最新商品图片路径，通过网络连接和流上传数据到 服务器
	 */
	public void uploadFile() {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\"" + newName + "\"" + end);
			ds.writeBytes(end);
			
			/* 取得文件的FileInputStream */// 读入响应
			FileInputStream fStream = new FileInputStream(uploadFile);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = fStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			Message msg = new Message();
			msg.what = WIN;
			msg.obj = b.toString();
			handler.sendMessage(msg);
			ds.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
